﻿using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace SunrayEngine.Maps
{
    [Serializable]
    public class MapGrid
    {
        #region fields
        private int width;
        private int height;
        public MapTile[,] Tiles;
        private Point[] tilesOnScreen;
        #endregion

        #region properties
        public Point[] TilesOnScreen { get { return tilesOnScreen; } }
        #endregion

        #region initialization
        public MapGrid(int offsetX, int offsetY, int width, int height, GraphicsDevice device, Rectangle bounds)
        {
            this.width = width;
            this.height = height;
            Tiles = new MapTile[width, height];

            for (int x = 0; x < width; x++)
                for (int y = 0; y < height; y++)
                    Tiles[y, x] = new MapTile(offsetX + (x * 32) + y * 32, offsetY + ((y * 16) + 30 + 16 * (Math.Abs(x - width))), 64, 32, device);

            UpdateTilesOnScreen(bounds);
        }
        #endregion

        #region methods
        public PixelInfo[,] GetPixelInfo()
        {
            int w = Tiles[0,0].Pixels.GetLength(0);
            int h = Tiles[0,0].Pixels.GetLength(1);
            PixelInfo[,] pixels = new PixelInfo[width * w, height * h];

            for(int x = 0; x < width; x++)
                for(int y = 0; y < height; y++)
                    for(int i = 0; i < w; i++)
                        for(int j = 0; j < h; j++)
                            pixels[(x * w), (y * h)] = Tiles[y,x].Pixels[i,j];

            return pixels;
        }

        public void EditOffset(Point p)
        {
            for (int x = 0; x < width; x++)
                for (int y = 0; y < height; y++)
                    Tiles[y, x].EditOffset(p);
        }

        public void Draw(SpriteBatch spriteBatch)
        {
            foreach(var p in tilesOnScreen)
                        Tiles[p.Y, p.X].Draw(spriteBatch);
        }

        public void DrawWalkabel(SpriteBatch spriteBatch)
        {
            foreach (var p in tilesOnScreen)
                Tiles[p.Y, p.X].DrawCollMap(spriteBatch);
        }

        public void UpdateTilesOnScreen(Rectangle bounds)
        {
            List<Point> points = new List<Point>();

            for (int x = 0; x < width; x++)
                for (int y = 0; y < height; y++)
                    if (Tiles[y, x].Bounds.Intersects(bounds))
                        points.Add(new Point(x, y));

            tilesOnScreen = points.ToArray();
        }
        #endregion
    }
}
